package com.yss.netty.protocol;

import lombok.Data;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Message to adapter
 */
@Data
public class Message {

    /**
     * Request identifier
     */
    private static final AtomicLong REQUEST_ID;

    static {
        REQUEST_ID = new AtomicLong(1);
    }

    public Message(final long opaque) {
        if (opaque == 0L) {
            this.opaque = REQUEST_ID.getAndIncrement();
        } else {
            this.opaque = opaque;
        }
    }

    /**
     * Message
     */
    private byte[] body;

    /**
     * Request serial number
     */
    private long opaque;

    /**
     * Serialization method
     */
    private SerType serType;

    /**
     * Data Type
     */
    private CommandType commandType;


    /**
     * The [client] is used to send messages,
     * which will cause the request sequence number to increase
     *
     * @param commandType
     * @param serType
     * @param body
     * @return
     */
    public static Message of(final CommandType commandType,
                             final SerType serType, final byte[] body) {
        return of(commandType, serType, body, 0L);
    }

    /**
     * The [server] is used for decoding
     * and will not cause an increase in the request sequence number
     *
     * @param commandType
     * @param serType
     * @param body
     * @param opaque
     * @return
     */
    public static Message of(final CommandType commandType,
                             final SerType serType, final byte[] body, long opaque) {
        Message message = new Message(opaque);
        message.setBody(body);
        message.setSerType(serType);
        message.setCommandType(commandType);
        return message;
    }

}
